<template>
    <div class="main_container">
        <div v-if="pageName=='index'" :style="{height: pageHeight+'px'}">
            <el-row style="height: 100%;">
                <el-col :span="3" style="border-right: 1px solid #eee;height: 100%;overflow-y: auto;">
                    <el-input placeholder="输入关键字" style="width: 150px;" v-model="filterText" clearable></el-input>
                    <el-tree 
                        ref="cateTree"
                        style="margin-top: 16px;"
                        :data="categorys" 
                        :props="defaultProps" 
                        node-key="id"
                        :current-node-key="-1"
                        empty-text="无分类数据"
                        :highlight-current="true"
                        :expand-on-click-node="true"
                        :indent="20"
                        :filter-node-method="filterNode"
                        @node-click="handleNodeClick"
                    ></el-tree>
                </el-col>
                <el-col :span="21" style="padding-left: 12px;">
                    <el-form :model="queryParams" label-width="auto">
                        <el-row>
                            <el-col :span="7">
                                <el-form-item label="关键词:">
                                    <el-input style="width: 200px;" maxlength="100" v-model="queryParams.search" 
                                        placeholder="商品编号/商品名称" @keyup.enter.native="handleQuery" 
                                        @clear="handleQuery" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item label="商品状态:">
                                    <el-select style="width: 200px;" v-model="queryParams.status" placeholder="请选择"
                                        @clear="handleQuery" @change="handleQuery" clearable>
                                        <el-option label="在售" value="active"></el-option>
                                        <el-option label="停售" value="inactive"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="创建日期:">
                                    <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                                        v-model="queryParams.create_datetime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                                        placeholder="请选择时间区间" style="width: 240px;" clearable></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="2">
                                <div style="display: flex;align-items: center;margin-top: 10px;" @click="showMore=!showMore">
                                    <span style="font-size: 14px;color: #606266;width: auto;cursor: pointer;margin-right: 5px;">高级搜索</span>
                                    <i :class="showMore?'el-icon-arrow-up':'el-icon-arrow-down'"></i>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row v-if="showMore">
                            <el-col :span="7">
                                <el-form-item label="规格:">
                                    <el-input style="width: 200px;" v-model="queryParams.specifications__icontains"
                                         placeholder="请输入" maxlength="20" @keyup.enter.native="handleQuery" 
                                         @clear="handleQuery" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item label="型号:">
                                    <el-input style="width: 200px;" v-model="queryParams.type__icontains"
                                         placeholder="请输入" maxlength="20" @keyup.enter.native="handleQuery" 
                                         @clear="handleQuery" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item label="品牌:">
                                    <el-input style="width: 200px;" v-model="queryParams.brand__icontains" 
                                        placeholder="请输入" maxlength="20" @keyup.enter.native="handleQuery" 
                                        @clear="handleQuery" clearable></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <el-row :gutter="16" class="mb8">
                        <el-button
                            style="margin: 0 18px 0 10px;"
                            class="btn_primary_color"
                            icon="el-icon-plus"
                            size="small"
                            @click="handleAdd"
                            v-hasPermi="['goods_add']"
                        >新增</el-button>
                            
                        <el-dropdown placement="bottom" @command="handleCommand">
                            <el-button type="primary" size="small" class="btn_primary_color">
                                批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item v-hasPermi="['import_product']" command="import">导入</el-dropdown-item>
                                <el-dropdown-item v-hasPermi="['export_product']" :disabled="multiple" command="export">导出所选</el-dropdown-item>
                                <el-dropdown-item v-hasPermi="['export_product']" command="exportAll">导出全部</el-dropdown-item>
                                <el-dropdown-item v-hasPermi="['goods_del']" :disabled="multiple" command="remove">删除所选</el-dropdown-item>
                                <el-dropdown-item v-hasPermi="['goods_barcode']" :disabled="multiple" command="barcode">批量生成条形码</el-dropdown-item>
                                <el-dropdown-item v-hasPermi="['goods_update_prices']" command="price">快捷改价</el-dropdown-item>
                                <el-dropdown-item v-hasPermi="['set_order_add']" command="cates">设置商品分类</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </el-row>

                    <el-table border :data="productList" style="margin-top: 15px;" :max-height="tableHeight"
                        @selection-change="handleSelectionChange" ref="prodTable">
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column label="商品图片" align="center" width="80" prop="imageUrl">
                            <template slot-scope="scope">
                                <el-popover
                                    placement="right"
                                    width="240"
                                    trigger="hover">
                                    <img :src="scope.row.imageUrl" style="width: 240px;height: 240px;" alt="">
                                    <img slot="reference" :src="scope.row.imageUrl" style="width: 32px;height: 32px;" alt="">
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column label="商品名称" min-width="100" header-align="center" show-overflow-tooltip align="left" prop="name" />
                        <el-table-column label="商品编号" width="100" align="center" prop="goods_no" />
                        <el-table-column label="商品分类" align="center" prop="cateName" />
                        <el-table-column label="单位" width="60" align="center" prop="unitName" />
                        <el-table-column label="零售价" align="center" prop="unit_retail_price" />
                        <el-table-column label="采购价" align="center" prop="unit_purchase_price" />
                        <el-table-column label="库存数量" align="center" prop="current_inventory_quantity" />
                        <el-table-column label="规格" align="center" prop="specifications" />
                        <el-table-column label="型号" align="center" prop="type" />
                        <el-table-column label="品牌" align="center" prop="brand" />
                        <el-table-column label="状态" width="60" align="center" prop="statusName" />
                        <el-table-column label="操作" width="130" fixed="right" header-align="center" align="left" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    type="text"
                                    @click="handleView(scope.row)"
                                    style="font-weight: bold;"
                                >查看</el-button>
                                <el-button
                                    size="mini"
                                    type="text"
                                    @click="handleEdit(scope.row)"
                                    style="font-weight: bold;"
                                    v-hasPermi="['goods_update']"
                                >编辑</el-button>
                                <el-button
                                    size="mini"
                                    type="text"
                                    @click="handleRemove(scope.row)"
                                    style="font-weight: bold;"
                                    v-hasPermi="['goods_del']"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        v-show="total>0"
                        background
                        style="padding: 32px 16px;background: #fff;text-align: right;"
                        @size-change="getProductLists"
                        @current-change="getProductLists"
                        :current-page.sync="pageParam.page"
                        :page-size="pageParam.num"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </el-col>   
            </el-row>
        </div>

        <!-- 新增页面 -->
        <common-dialog :visiable="pageName == 'addProduct'">
            <add-prodcut :corpId="corp_id" @hidden="hidden" @success="success"></add-prodcut>
        </common-dialog>
        <!-- 编辑页面 -->
        <common-dialog :visiable="pageName == 'editProduct'">
            <add-prodcut :corpId="corp_id" :editId="editId" @hidden="hidden" @success="success"></add-prodcut>
        </common-dialog>
        <!-- 批量改价 -->
        <common-dialog :visiable="pageName == 'updatePrice'">
            <update-price :corpId="corp_id" @hidden="hidden"></update-price>
        </common-dialog>
        <!-- 查看页面 -->
        <common-dialog :visiable="pageName == 'queryProduct'">
            <query-prodcut :corpId="corp_id" :editId="editId" @hidden="hidden"></query-prodcut>
        </common-dialog>

        <el-drawer
            title="设置商品分类"
            append-to-body
            :visible.sync="showCategorySet"
            :wrapperClosable="false"
            :before-close="handleClose">
            <div class="cates_view">
                <div class="tops">
                    <el-input placeholder="输入关键字进行过滤" style="width: 200px;" v-model="filterText1" clearable></el-input>
                    <el-button class="btn_primary_color" icon="el-icon-plus" size="small" @click="handleAddCategory">新增一级分类</el-button>
                </div>
                <el-tree
                    ref="cateTree1"
                    style="margin-top: 15px;"
                    :data="cateLists"
                    :props="defaultProps" 
                    node-key="id"
                    empty-text="无分类数据"
                    default-expand-all
                    :indent="20"
                    :filter-node-method="filterNode"
                    :expand-on-click-node="false">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span class="custom_label">{{ node.label }}</span>
                        <span style="width: 145px;display: inline-flex;justify-content: end;">
                            <el-button
                                v-if="node.level=='1'"
                                type="text"
                                size="mini"
                                @click="() => handleAddCategory(data)">
                                新增子分类
                            </el-button>
                            <el-button
                                type="text"
                                size="mini"
                                @click="() => handleEditCategory(data)">
                                编辑
                            </el-button>
                            <el-button
                                type="text"
                                size="mini"
                                @click="() => handleRemoveCategory(data)">
                                删除
                            </el-button>
                        </span>
                    </span>
                </el-tree>
            </div>
        </el-drawer>

        <el-dialog
            :title="cateEditDialogTitle"
            :visible.sync="showCategoryAdd"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="cateInfo" label-width="auto" ref="cateForm" :rules="rules">
                    <el-form-item label="分类名称:" prop="name">
                        <el-input style="width: 240px;" maxlength="100" v-model="cateInfo.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showCategoryAdd=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addProductCategory">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 导入弹窗 -->
        <el-dialog
            title="导入商品"
            :visible.sync="showImport"
            width="40%"
            append-to-body
            @close="closeImport"
            :close-on-click-modal="false"
            center>
            <div class="upload_view">
                <el-upload drag
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-remove="handleRemoveFile"
                    :http-request="(params) => uploadSectionFile(params, 'picUpload')" 
                    :accept="picUpload.accept.join(',')"
                    :file-list="fileList"
                    action="anything">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">
                        <div style="display: flex;align-items: center;justify-content: space-between;">
                            <span>只能上传{{ picUpload.accept.join('、') }}文件，且不超过{{ picUpload.max }}MB</span>
                            <span style="color: #068CEE;cursor: pointer;" @click="downloadTemplate">下载模板</span>
                        </div> 
                        <div v-if="showImportError" style="display: flex;align-items: center;justify-content: space-between;color: red;margin-top: 10px;">
                            <span class="shake_words">{{ taskInfo.error_msg }}</span>
                            <span style="color: #068CEE;cursor: pointer;" @click="downloadFail">下载导入失败文件</span>
                        </div>
                    </div>
                </el-upload>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button class="btn_primary_color" @click="startUpload">开始导入</el-button>
            </span>
        </el-dialog>

        <input type="text" id="scanCodeGun" v-model="scanCode" autofocus class="hide_input">
    </div>
</template>

<script>
import commonDialog from "@/components/commonDialog";
import { commonUpload } from '@/api/util';
import { baseUrl } from '@/config/env';
import { addDownloadTask, addImportTask, getImportTaskInfo } from '@/api/common';
import { getTreeList, removeProduct, listProduct, addTreeItem, updateBarcode,
    editTreeItem, removeTreeItem, removeBatchProduct } from '@/api/product';
const moment = require('moment')

export default {
    name: 'productList',
    data() {
        return {
            fullPageLoading: null,  //全屏loading
            showImportError: false,
            showImport: false,
            showMore: false,
            pageHeight: 0,
            tableHeight: 0,
            picUpload: {
                max: 10,
                accept: ['.xls', '.xlsx']
            },
            fileList: [],
            uploadParam: {},
            taskInfo: {},
            timer: null,
            exportParam: {
                corp_id: '',
                params: {},
                task_type: 'export_product',
                params_method: 0,
                file_name: '商品'+moment().format('yyyyMMDDHHmmss')+'.xlsx'
            },
            exportLoading: false,
            showCategorySet: false,
            showCategoryAdd: false,
            showCustomerInfo: false,
            cateEditDialogTitle: '',
            multiple: true, // 非多个禁用
            corp_id: '',
            editId: null,  //订单id
            pageName: 'index',
            filterText: '',
            filterText1: '',
            queryParams: {
                search: '',
                status: null,
                brand__icontains: '',
                type__icontains: '',
                specifications__icontains: '',
                create_datetime: [],
                create_datetime__lte: '',  //小于等于
                create_datetime__gte: '',  //大于等于
                category_one_level: '',  //一级分类
                category: '',    //二级分类
                ordering: '-update_datetime,-id'
            },
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            productList: [],
            categorys: [],  //一级分类
            subCategorys: [],  //二级分类
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            cateLists: [],
            cateInfo: {
                name: '',
                parent_id: null,
                description: '',
                corp: ''
            },
            rules:{
                name: [
                    { required: true, message: "请输入分类名称", trigger: "blur" },
                ],
            },
            selectIds: [],
            updatePricesList: [],
            scanCode: ''
        }
    },
    watch: {
        'queryParams.create_datetime': {
            handler(value){
                if(value){
                    this.queryParams.create_datetime__lte = value[1]
                    this.queryParams.create_datetime__gte = value[0]
                }
                else{
                    this.queryParams.create_datetime__lte = this.queryParams.create_datetime__gte = null
                }
                this.handleQuery()
            },
            deep: true
        },
        filterText(val) {
            this.$refs.cateTree.filter(val);
        },
        filterText1(val) {
            this.$refs.cateTree1.filter(val);
        },
        showMore(val) {
            if (val){
                this.tableHeight = this.pageHeight - 190 - 62
            }else {
                this.tableHeight = this.pageHeight - 190
            }
            this.$refs.prodTable.doLayout()
        }
    },
    components: {
        commonDialog,
        addProdcut: () => import('./add.vue'),
        updatePrice: () => import('./updatePrice.vue'),
        queryProdcut: () => import('./query.vue'),
    },
    created() {
        this.corp_id = this.$store.state.corpId
        this.exportParam.corp_id = this.corp_id
        this.cateInfo.corp = this.corp_id
        this.getProductCates()
        this.getProductLists()
        
        document.addEventListener('keydown', this.getScanCode)
        document.addEventListener('focusout', this.setInputFocus)
        document.addEventListener('click', this.checkWhichIsActive)
        let that = this
        this.$nextTick(() => {
            document.getElementById('scanCodeGun').focus()
            that.pageHeight = window.innerHeight - 140
            that.tableHeight = that.pageHeight - 190
        })
    },
    beforeDestroy() {
        document.removeEventListener('keydown', this.getScanCode)
        document.removeEventListener('focusout', this.setInputFocus)
    },
    methods: {
        getScanCode(e) {
            if (e.key=='Enter' && e.target.id=='scanCodeGun'){
                // alert('扫描结果 --- '+e.target.value)
                this.queryParams.goods_unit_deputy__barcode = e.target.value
                this.handleQuery()
                this.scanCode = ''
            }
        },
        setInputFocus(e) {
            if (e.target.id != 'scanCodeGun'){
                document.getElementById('scanCodeGun').focus()
            }
        },
        checkWhichIsActive(e) {
            const inputElement = document.getElementById('scanCodeGun');
            if (document.activeElement.tagName=='BODY' && document.activeElement!=inputElement){
                document.getElementById('scanCodeGun').focus()
            }
        },
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.getProductLists()
        },
        // 获取商品分类
        getProductCates() {
            let that = this
            getTreeList({corp: this.corp_id}).then(res => {
                if (res.data.data.category_list.length){
                    let categorys = res.data.data.category_list.filter(item => { return !item.parent })
                    categorys.unshift({
                        id: -1,
                        level: 'one',
                        name: '全部分类',
                        parent: null,
                        description: '',
                        children: []
                    })
                    categorys = categorys.filter(item => {
                        item.label = item.name
                        item.level = 'one'  //一级分类
                        if (item.children && item.children.length){
                            item.children = item.children.filter(_item => {
                                _item.parentId = item.id
                                _item.label = _item.name
                                _item.level = 'two'  //二级分类
                                return _item
                            })
                        }
                        return item
                    })
                    that.categorys = categorys
                    that.cateLists = categorys.slice(1)
                }
            })
        },
        // 获取商品列表
        getProductLists() {
            this.queryParams.corp = this.corp_id
            let params = Object.assign({}, this.queryParams, this.pageParam)
            delete params['create_datetime']
            listProduct(params).then(res => {
                let list = res.data.data.good_list.filter(item => {
                    item.cateName = item.category_detail.name
                    if (item.image_show && item.image_show.url){
                        item.imageUrl = item.image_show.url
                    }else{
                        item.imageUrl = 'https://anhuiyaoying.com/icon/default.png'
                    }
                    item.goods_no = item.goods_no || ''
                    item.statusName = item.status=='active'?'在售':'停售'
                    let mainUnitItem = item.unit_deputy_show.find(el => el.is_main)
                    item.unit_purchase_price = mainUnitItem.unit_purchase_price?mainUnitItem.unit_purchase_price:'--'
                    item.unit_retail_price = mainUnitItem.unit_retail_price?mainUnitItem.unit_retail_price:'--'
                    item.current_inventory_quantity = parseFloat(item.current_inventory_quantity)
                    item.unitName = item.unit_show?item.unit_show.name:''
                    return item
                })
                this.productList = list
                this.total = res.data.data.total
                this.queryParams.goods_unit_deputy__barcode = ''
            }) 
        },
        // 商品分类筛选
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 商品分类点击
        handleNodeClick(data) {
            let level = data.level
            if (level == 'one'){
                this.queryParams.category_one_level = data.id
                if (data.id == -1){
                    this.queryParams.category_one_level = null
                }
                this.queryParams.category = null
            }else if (level == 'two'){
                this.queryParams.category_one_level = null
                this.queryParams.category = data.id
            }
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            // console.log(selection);
            this.multiple = !selection.length
            let ids = selection.map(item => item.id)
            this.selectIds = ids
            this.selectLists = selection
            if (ids.length){
                this.exportParam.params.id_list = ids.join(',');
            }
        },
        handleCommand(command) {
            switch (command) {
                case 'import':
                    this.handleImport()
                    break;
                case 'export':
                    this.handleExport()
                    break;
                case 'exportAll':
                    this.handleExport('all')
                    break;
                case 'remove':
                    this.handleRemoveSelect()
                    break;
                case 'barcode':
                    this.handleCreateBarcode()
                    break;
                case 'price':
                    this.handleUpdatePrices()
                    break;
                case 'cates':
                    this.handleSetting()
                    break;   
                default:
                    break;
            }
        },
        // 新增
        handleAdd() {
            this.editId = null
            this.pageName = 'addProduct'
        },
        // 编辑
        handleEdit(item) {
            this.editId = item.id
            this.pageName = 'editProduct'
        },
        // 批量生成条形码
        handleCreateBarcode() {
            updateBarcode({
                corp_id: this.corp_id,
                query_params: {
                    corp: this.corp_id,
                    id_list: this.selectIds.join(',')
                }
            }).then(res => {
                if (res.code == 200){
                    this.handleQuery()
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    })
                } 
            })
        },
        // 快捷改价
        handleUpdatePrices() {
            this.pageName = 'updatePrice'
        },
        // 删除所选
        handleRemoveSelect() {
            let that = this
            this.$confirm('您确定要删除选中的商品吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeBatchProduct({
                    corp_id: that.corp_id,
                    pk_id_list: that.selectIds
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 删除单个
        handleRemove(item) {
            let that = this
            this.$confirm('您确定要删除该商品吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeProduct(item.id, {
                    corp: that.corp_id
                }).then(res => {
                    if (res.code == 200){
                        that.handleQuery()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        // 查看
        handleView(item) {
            this.editId = item.id
            this.pageName = 'queryProduct'
        },
        // 导入
        handleImport() {
            this.showImportError = false
            this.showImport = true
        },
        closeImport() {
            this.uploadParam = {}
            this.fileList = []
            this.showImport = false
        },
        // 导出
        handleExport(type) {
            this.exportParam.params = Object.assign({}, this.exportParam.params, this.queryParams)
            if (type && type=='all'){
                delete this.exportParam.params['id_list']
            }
            delete this.exportParam.params['create_datetime']
            
            addDownloadTask(this.exportParam).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: '文件正在下载中，请至任务列表中查看',
                        type: 'success',
                        duration: 2000
                    })
                    this.$store.dispatch('GetTaskList', this.corp_id); 
                    this.$store.dispatch('startInterval')
                }
            })
        },
        // 设置商品分类
        handleSetting() {
            this.showCategorySet = true
        },
        
        handleClose(done){
            done();
        },
        // 新增分类
        handleAddCategory(item) {
            this.cateInfo.name = ''
            if (item && item.id) {
                this.cateInfo.parent_id = item.id
                this.cateEditDialogTitle = '新增子分类'
            }else{
                this.cateEditDialogTitle = '新增一级分类'
            }
            this.showCategoryAdd = true
        },
        addProductCategory() {
            var that = this
            that.$refs['cateForm'].validate(valid => {
                if(!valid) return

                let temp = null
                if (that.cateInfo.id) {
                    temp = editTreeItem(that.cateInfo.id,that.cateInfo)
                }else{
                    temp = addTreeItem(that.cateInfo)
                }
                temp.then(res => {
                    if (res.code == 200){
                        that.cateInfo.name = ''
                        that.cateInfo.parent_id = null
                        that.cateInfo.id = null
                        that.getProductCates()
                        that.showCategoryAdd = false
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        // 编辑分类
        handleEditCategory(item) {
            console.log(item)
            this.cateInfo.name = item.name
            this.cateInfo.id = item.id
            this.cateInfo.parent_id = item.parentId
            this.cateEditDialogTitle = '编辑商品分类'
            this.showCategoryAdd = true
        },
        // 删除分类
        handleRemoveCategory(item) {
            let that = this
            this.$confirm('您确定要删除该商品分类吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeTreeItem(item.id, {
                    corp: that.corp_id
                }).then(res => {
                    if (res.code == 200){
                        that.getProductCates()
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
					}
                })
            }).catch(() => {        
            });
        },
        hidden(res) {
            console.log(res)
            if (res && res.isRefresh){
                this.getProductCates()
                this.handleQuery()
            }
            this.pageName = 'index'
        },
        success() {
            this.handleQuery()
            this.pageName = 'index'
        },
        //  ------------------------------- 文件上传相关 --------------------------------
        // 文件超出个数限制时
        handleExceed() {
            this.$message.warning('只能上传一个文件，若需要重新上传，请先删除已上传文件')
        },
        // 文件列表移除文件
        handleRemoveFile() {
            this.uploadParam = {}
        },
        // 上传前校验
        beforeUpload (file, uploadType) {
            let isRightSize = file.size / 1024 / 1024 < this[uploadType].max
            if (!isRightSize) {
                this.$message.error('文件大小超过' + this[uploadType].max + 'MB')
            }
            let fileArr = file.name.split('.')
            let ext = fileArr[fileArr.length - 1]
            let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + ext.toLowerCase())
            if (!isAccept) {
                this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
            }
            return isRightSize && isAccept
        },
        // 附件上传
        uploadSectionFile (params, uploadType) {
            let _this = this
            if (!this.beforeUpload(params.file, uploadType)) {
                params.onError()
                return
            }
            
            let param = {
                corp: _this.corp_id,
                user: _this.$store.state.userInfo.id,
                file_path: params.file
            }
            commonUpload('/commons/inner_upload_file_view', param).then(res => {
                if (res.code == 200){
                    _this.$message.success('上传成功')
                    _this.uploadParam = res.data
                }else{
                    _this.$message.error('上传失败，请重新上传')
                    _this.uploadParam = {}
                } 
            })
        },
        // 开始上传
        startUpload() {
            if (Object.keys(this.uploadParam).length === 0){
                this.$message.error('请先上传要导入的文件')
                return
            }

            let that = this
            addImportTask({
                corp_id: this.uploadParam.corp,
                file_upload_id: this.uploadParam.id,
                task_type: 'import_product',
                file_name: ''
            }).then(res => {
                if (res.code == 200){
                    that.fullPageLoading = that.$loading({
                        lock: true,
                        text: '正在导入数据，请稍候...',
                        spinner: 'el-icon-loading',
                        // background: 'rgba(0, 0, 0, 0.7)'
                    });
                    that.timer = setInterval(() => {
                        that.getTaskStatus(res.data.id)
                    }, 5000);
                }
            })
        },
        // 获取导入任务详情
        getTaskStatus(pk_id) {
            let corp = this.corp_id
            getImportTaskInfo({corp, pk_id}).then(res => {
                let task_status = res.data.task_status
                if (task_status == 1){  //导入成功
                    clearInterval(this.timer)
                    this.fullPageLoading.close()
                    this.showImport = false
                    this.$message.success('导入成功')
                    this.getProductCates()
                    this.handleQuery()
                }else if (task_status==2 || task_status==4){  //导入失败
                    clearInterval(this.timer)
                    this.fullPageLoading.close()
                    this.showImportError = true
                    this.taskInfo = res.data
                    this.taskInfo.error_msg = res.data.error_msg? ('导入失败：'+res.data.error_msg) : '导入失败'
                    this.getProductCates()
                    this.handleQuery()
                }
            })
        },
        // 下载导入失败文件
        downloadFail() {
            let url = baseUrl+'/commons/download_import_error_file_view?pk_id='+this.taskInfo.id+'&token='+this.taskInfo.token+
				'&execute_time_unix='+this.taskInfo.execute_time_unix
                let that = this
				fetch(url).then(response => {
						if (!response.ok) {
							throw new Error('Network response was not ok');
						}
						return response.blob(); // 将响应转换为 Blob 对象
					})
					.then(blob => {
						const url = window.URL.createObjectURL(blob); // 创建一个指向 Blob 的 URL
						const a = document.createElement('a'); // 创建一个 <a> 元素
						a.style.display = 'none';
						a.href = url;
						a.download = '导入失败文件.xlsx'; // 设置下载的文件名
						document.body.appendChild(a);
						a.click(); // 模拟点击下载
						window.URL.revokeObjectURL(url); // 释放 Blob URL
						document.body.removeChild(a); // 移除 <a> 元素
						that.showPop = true
					})
					.catch(error => console.error('下载文件时出错:', error));
        },
        // 模板下载
        downloadTemplate() {
            window.location.href = 'https://anhuiyaoying.com/webs/template/%E4%BA%A7%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx'
        }
    }
}
</script>

<style lang="less" scoped>
	@import '../../style/mixin';
    .cates_view {
        padding: 0 30px 30px 30px;
        .tops {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
    }
    .upload_view {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .hide_input {
        opacity: 0;
        position: fixed;
        right: 0;
        top: 0;
    }
</style>

<style>
.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background: #068CEE !important;
    color: #fff !important;
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    width: 100%;
}
.el-loading-spinner {
    top: 42% !important;
    color: #068CEE !important;
}
.el-loading-spinner .el-icon-loading {
    font-size: 34px !important;
    margin-bottom: 15px !important;
}
.el-loading-spinner .el-loading-text {
    font-size: 16px !important;
}
.el-tree-node__label {
    width: 100% !important;
    white-space: nowrap !important; 
    overflow: hidden !important; 
    text-overflow: ellipsis !important;
}
.custom_label {
    width: 180px;
    white-space: nowrap !important; 
    overflow: hidden !important; 
    text-overflow: ellipsis !important;
}
</style>